﻿using Elderlyhealth.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;// 引入 EntityFunctions 需要的命名空间

public partial class AbAlerts : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 每次加载页面时都执行这些操作
            LoadAlerts();
            SendEmailAlertsForPendingAlerts(); // 页面加载时发送未处理警报的邮件通知

            int elderId = GetBoundElderId(); // 动态获取绑定的老人 ID
            if (elderId > 0)
            {
                DisplayRiskLevel(elderId); // 传递正确的老人 ID

                // 调用改进后的 GetAlertTrendData 方法，传入 elderId
                var alertTrendData = GetAlertTrendData(elderId);
                var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(alertTrendData, new Newtonsoft.Json.JsonSerializerSettings
                {
                    DateFormatString = "yyyy-MM-dd"
                });
                ClientScript.RegisterStartupScript(this.GetType(), "alertTrendData", $"<script>var alertTrendData = {jsonData};</script>", false);
            }

        }
    }
        // 获取动态绑定的老人 ID
        // 从数据库或 Session 中获取当前用户绑定的老人 ID
        private int GetBoundElderId()
    {
        // 假设老人 ID 存储在 Session 中，或从数据库查询获取
        if (Session["BoundElderId"] != null)                                                                                                                                                                                                                                                     
        {
            return Convert.ToInt32(Session["BoundElderId"]);
        }
        else
        {
            // 如果没有从 Session 获取，直接从数据库查询
            int childId = GetLoggedInChildId();
            using (var dbContext = new DataClasses1DataContext())
            {
                var elderId = dbContext.RelativeOldMapping
                                        .Where(b => b.子女id == childId && b.审核状态 == true)
                                        .Select(b => b.老人id)
                                        .FirstOrDefault();
                return elderId;
            }
        }
    }
    private void DisplayRiskLevel(int oldId)
    {
        if (oldId == -1)
        {
            Console.WriteLine("未找到绑定的老人 ID。");
            return;
        }

        // 查询过去30天的异常次数
        int abnormalCount = GetAbnormalCountForOldId(oldId);

        // 设置风险等级和显示的样式
        string riskLevel = GetRiskLevel(abnormalCount);
        string progressClass;
        int progressPercentage;

        switch (riskLevel)
        {
            case "低风险":
                progressClass = "low-risk";
                progressPercentage = 33;
                break;
            case "中风险":
                progressClass = "medium-risk";
                progressPercentage = 66;
                break;
            case "高风险":
                progressClass = "high-risk";
                progressPercentage = 100;
                break;
            default:
                progressClass = "low-risk";
                progressPercentage = 0;
                break;
        }

        // 生成前端 JavaScript 代码，动态更新进度条
        ClientScript.RegisterStartupScript(this.GetType(), "SetRiskLevel", $@"
        document.getElementById('riskProgress').className = 'progress {progressClass}';
        document.getElementById('riskProgress').style.width = '{progressPercentage}%';
        document.getElementById('riskLabel').innerText = '{riskLevel}';
    ", true);
    }

    private int GetAbnormalCountForOldId(int oldId)
    {
        using (var dbContext = new DataClasses1DataContext())
        {
            // 查询过去30天内的待处理异常警报数量
            return dbContext.Talerts警报
                            .Where(a => a.old_id == oldId &&
                                        a.状态 == "待处理" &&   // 确保只统计未处理的异常
                                        a.时间 >= DateTime.Now.AddDays(-30)) // 仅限过去30天内
                            .Count();
        }
    }


    private string GetRiskLevel(int abnormalCount)
    {
        if (abnormalCount < 3)
            return "低风险";
        else if (abnormalCount < 6)
            return "中风险";
        else
            return "高风险";
    }

    public void SendEmailAlertsForPendingAlerts()
    {
        int userId = GetLoggedInChildId();

        using (var dbContext = new DataClasses1DataContext())
        {
            // 查询该用户的待处理警报，且未发送邮件通知的记录
            var alerts = from notification in dbContext.TNotification警报通知
                         join alert in dbContext.Talerts警报 on notification.AlertId equals alert.警报id
                         join relative in dbContext.Trelative子女 on notification.UserId equals relative.子女id
                         where notification.UserId == userId
                               && notification.IsEmailSent == false
                               && alert.状态 == "待处理" // 确保警报状态是待处理
                         select new { notification, alert.描述, relative.邮箱 };

            if (!alerts.Any())
            {
                Console.WriteLine("未找到符合条件的待处理警报，无法发送邮件通知。");
                return;
            }

            foreach (var item in alerts)
            {
                string subject = "异常警报通知";
                string body = $"尊敬的用户，您的老人有新的异常警报：{item.描述}";

                Console.WriteLine($"正在发送邮件至 {item.邮箱}，内容：{item.描述}");

                // 发送邮件
                if (SendEmail(item.邮箱, subject, body))
                {
                    // 如果邮件发送成功，将 IsEmailSent 更新为 true，避免重复发送
                    item.notification.IsEmailSent = true;
                    Console.WriteLine("邮件发送成功，并更新通知状态。");
                }
                else
                {
                    Console.WriteLine("邮件发送失败。");
                }
            }

            dbContext.SubmitChanges(); // 保存更新到数据库
        }
    }



    public bool SendEmail(string toEmail, string subject, string body)
    {
        try
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("527379257@qq.com"); // 发件人地址
            mail.To.Add(toEmail); // 收件人地址
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;

            SmtpClient smtpClient = new SmtpClient("smtp.qq.com"); // QQ的SMTP服务器
            smtpClient.Port = 587;
            smtpClient.Credentials = new System.Net.NetworkCredential("527379257@qq.com", "ckyotszzhcodbief"); // QQ邮箱授权码
            smtpClient.EnableSsl = true;

            smtpClient.Send(mail);
            return true; // 邮件发送成功
        }
        catch (Exception ex)
        {
            Console.WriteLine("发送邮件失败: " + ex.Message);
            Response.Write("<script>alert('发送邮件失败: " + ex.Message + "');</script>");
            return false; // 邮件发送失败
        }
    }

    private void LoadAlerts()
    {
        int childId = GetLoggedInChildId();

        using (var dbContext = new DataClasses1DataContext())
        {
            var boundElderIds = dbContext.RelativeOldMapping
                                         .Where(b => b.子女id == childId && b.审核状态 == true)
                                         .Select(b => b.老人id)
                                         .ToList();

            if (!boundElderIds.Any())
            {
                Response.Write("<script>alert('未找到绑定的老人');</script>");
                return;
            }

            var alerts = dbContext.Talerts警报
                                  .Where(a => boundElderIds.Contains(a.old_id))
                                  .OrderByDescending(a => a.时间)
                                  .Select(a => new
                                  {
                                      a.警报id,
                                      a.警报类型,
                                      a.描述,
                                      a.时间,
                                      a.状态
                                  })
                                  .ToList();

            AlertGridView.DataSource = alerts;
            AlertGridView.DataBind();
        }
    }

    protected void HandleButton_Click(object sender, EventArgs e)
    {
        Button handleButton = (Button)sender;
        int alertId = int.Parse(handleButton.CommandArgument);

        using (var dbContext = new DataClasses1DataContext())
        {
            var alert = dbContext.Talerts警报.SingleOrDefault(a => a.警报id == alertId);
            if (alert != null && alert.状态 == "待处理")
            {
                alert.状态 = "已处理";
                dbContext.SubmitChanges();

                // 添加通知记录
                AddNotification(alert.警报id, GetLoggedInChildId());
            }
        }

        // 重新加载警报列表
        LoadAlerts();
    }

    private void AddNotification(int alertId, int userId)
    {
        using (var dbContext = new DataClasses1DataContext())
        {
            var alert = dbContext.Talerts警报.SingleOrDefault(a => a.警报id == alertId);

            if (alert != null)
            {
                var notification = new TNotification警报通知
                {
                    UserId = userId,
                    AlertMessage = alert.描述,  // 使用警报表中的描述填充通知消息
                    AlertId = alertId,          // 确保此处正确设置 AlertId
                    IsEmailSent = false,
                    IsPushSent = true           // 假设推送通知已实现
                };

                dbContext.TNotification警报通知.InsertOnSubmit(notification);
                dbContext.SubmitChanges();
            }
        }
    }
    /*public void TestManualEmail()
    {
        string toEmail = "527379257@qq.com";
        string subject = "测试邮件";
        string body = "这是一个测试邮件，用于确认邮件发送配置是否正常。";

        bool result = SendEmail(toEmail, subject, body);
        if (result)
        {
            Console.WriteLine("手动测试邮件发送成功");
        }
        else
        {
            Console.WriteLine("手动测试邮件发送失败");
        }
    }*/
    private int GetLoggedInChildId()
    {
        return Convert.ToInt32(Session["CustomerId"]);
    }

    public class AlertTrendData
    {
        public DateTime 日期 { get; set; }
        public int 警报数量 { get; set; }
        

    }

    public List<AlertTrendData> GetAlertTrendData(int elderId)
    {
        using (var dbContext = new DataClasses1DataContext())
        {
            var alertTrendData = dbContext.Talerts警报
                .Where(a => a.old_id == elderId && a.时间.HasValue && a.时间.Value >= DateTime.Now.AddDays(-60))
                .GroupBy(a => a.时间.Value.Date) // 确保 a.时间 为非空
                .Select(g => new AlertTrendData
                {
                    日期 = g.Key,
                    警报数量 = g.Count()
                })
                .OrderBy(data => data.日期)
                .ToList();

            return alertTrendData;
        }
    }



}


